import { ref, onMounted } from 'vue'

export function useTampermonkey() {
  const isTampermonkey = ref(false)

  // 检查环境
  const checkEnvironment = () => {
    isTampermonkey.value = typeof GM !== 'undefined'
    return isTampermonkey.value
  }

  // 添加样式 (确保样式全局生效)
  const addStyle = (css) => {
    if (isTampermonkey.value) {
      GM_addStyle(css)
      return true
    }

    // 非TM环境降级处理
    const style = document.createElement('style')
    style.textContent = css
    document.head.appendChild(style)
    return false
  }

  // 添加全局样式
  const addGlobalStyles = () => {
    const css = `
    body > #vue-devtools-container {
      all: initial !important;
      position: fixed !important;
      top: 0 !important;
      left: 0 !important;
      z-index: 2147483647 !important;
      /* 移除 pointer-events: none */
    }
    
    /* 保护层样式 */
    .vue-devtools-protector {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1000000;
      pointer-events: none;
    }
  `
    addStyle(css)
  }

  // 初始化
  onMounted(() => {
    checkEnvironment()
    addGlobalStyles()
  })

  return {
    isTampermonkey,
    addGlobalStyles,
    addStyle
  }
}
